<style>
  .layui-form-label {
    width: 100px;
  }
  .layui-input-block {
    margin-left: 130px;
  }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <div class="layui-inline">
                  <label class="layui-form-label w-auto">名称：</label>
                  <div class="layui-input-inline">
                    <input name="name" class="layui-input" type="text" placeholder="请输入名称" autocomplete="off" />
                  </div>
                </div>
                <div class="layui-inline">
                  <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                  <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                </div>
              </div>
              <div class="query-rt"></div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt">
              <button id="producCategorySystemBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
              <button id="syncProductCategory" class="layui-btn icon-btn color-reseda">同步</button>

            </div>
            <div class="lay-btn-rt"></div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-bor">
        <table class="layui-table" id="producCategorySystemTable" lay-filter="producCategorySystemTable"></table>
      </div>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="producCategorySystemTableBar">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
  {{# if(!d.isFinal){ }}
  <a class="layui-btn layui-btn-xs" lay-event="addSub">添加子分类</a>
  {{# } }}
  <!--{{# if(!d.hasChild){ }}-->
  <!--<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
  <!--{{# } }}-->
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="producCategorySystemForm">
  <form lay-filter="producCategorySystemForm" class="layui-form model-form">
    <input name="id" type="hidden" />

    <div class="layui-form-item" id="PID">
      <label class="layui-form-label">所属分类</label>
      <input name="parentId" type="hidden" />
      <div class="layui-input-block" id="selectCategory"></div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">名称</label>
      <div class="layui-input-block">
        <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required autocomplete="off" />
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">描述</label>
      <div class="layui-input-block">
        <textarea id="remark" name="remark" placeholder="请输入描述" class="layui-textarea" autocomplete="off" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">分类类型</label>
      <div class="layui-input-block">
        <select name="categoryType" lay-verify="required">
          <option value="">请选择</option>
          <option value="purchase" selected>采购物资</option>
          <option value="production">产成品</option>
          <option value="sell">其他可销售物资</option>
          <option value="asset">资产</option>
          <option value="other">其他</option>
        </select>
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">是否终极分类</label>
      <div class="layui-input-block">
        <input name="isFinal" type="checkbox" lay-skin="switch" value="1" lay-text="终极分类|非终极分类" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否刀具分类</label>
      <div class="layui-input-block">
        <input name="type" id="type" type="checkbox" lay-skin="switch" checked lay-text="刀具分类|非刀具分类" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否启用</label>
      <div class="layui-input-block">
        <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">排序</label>
      <div class="layui-input-block">
        <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required autocomplete="off" />
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="producCategorySystemFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<script type="text/html" id="childForm">
  <form lay-filter="producCategorySystemForm" class="layui-form model-form">
    <input name="id" type="hidden" />
    <input name="parentId" type="hidden" />

    <div class="layui-form-item">
      <label class="layui-form-label">名称</label>
      <div class="layui-input-block">
        <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required" required autocomplete="off" />
      </div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">描述</label>
      <div class="layui-input-block">
        <textarea name="remark" placeholder="请输入描述" class="layui-textarea" autocomplete="off" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">分类类型</label>
      <div class="layui-input-block">
        <select name="categoryType">
          <option value="">请选择</option>
          <option value="purchase">采购物资</option>
          <option value="production">生产物料</option>
          <option value="sell">销售物资</option>
          <option value="asset">资产</option>
          <option value="other">其他</option>
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否终极分类</label>
      <div class="layui-input-block">
        <input name="isFinal" type="checkbox" lay-skin="switch" value="1" lay-text="终极分类|非终极分类" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否启用</label>
      <div class="layui-input-block">
        <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false" lay-text="启用|停用" />
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">排序</label>
      <div class="layui-input-block">
        <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required autocomplete="off" />
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="childFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<!-- js部分 -->
<script>
  layui.use(['layer', 'form', 'table', 'laydate', 'admin', 'laytpl', 'tableTreeDj', 'config'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var laydate = layui.laydate;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    var tableTree = layui.tableTreeDj;

    // 渲染表格
    var insTb = tableTree.render(
      {
        id: '#producCategorySystemTable',
        elem: '#producCategorySystemTable',
        url: config.base + 'enterprise/system/admin/productCategorySystem/list?limit=9999&enterprise=0',
        toolbar: true,
        defaultToolbar: ['filter'],
        page: false,
        cellMinWidth: 100,
        cols: [
          [
            { type: 'checkbox' },
            { field: 'name', sort: true, title: '物料分类名称' },
            { field: 'categoryTypeDesc', sort: true, title: '分类类型' },
            { field: 'remark', sort: true, title: '描述' },

            { field: 'createTime', sort: true, title: '创建时间' },
            { field: 'sortNumber', sort: true, title: '排序' },
            {
              field: 'type',
              sort: true,
              title: '是否刀具分类',
              templet: function (d) {
                return d.type == 'cabnet' ? '非刀具分类' : '刀具分类';
              },
            },
            {
              field: 'isDeleted',
              sort: true,
              title: '是否启用',
              templet: function (d) {
                if (d.hasEnableChild) {
                  if (d.isDeleted) {
                    return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用" disabled/>';
                  } else {
                    return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                  }
                } else {
                  if (d.isDeleted) {
                    return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用"/>';
                  } else {
                    return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                  }
                }
              },
            },
            { align: 'center', toolbar: '#producCategorySystemTableBar', title: '操作', width: 300 },
          ],
        ],
        done: function (res, curr, count) {
          //移除按钮
          var menuButton = config.getMenuButton(location.hash);
          if (menuButton.indexOf('搜索') == -1) {
            $('.layui-form.toolbar').remove();
          }
          if (menuButton.indexOf('修改') == -1) {
            $("[lay-event='edit']").remove();
          }
          if (menuButton.indexOf('删除') == -1) {
            $("[lay-event='del']").remove();
          }
        },
      },
      { keyPid: 'parentId', title: 'name' },
    );

    // 工具条点击事件
    table.on('tool(producCategorySystemTable)', function (obj) {
      var data = obj.data;
      if (obj.event === 'edit') {
        //修改
        showEditModel(data, 'producCategorySystemForm', 'producCategorySystemFormSubmit');
      } else if (obj.event === 'del') {
        // 删除
        doDelete(obj);
      } else if (obj.event === 'addSub') {
        //添加子级分类
        showEditModel(data, 'childForm', 'childFormSubmit', data.id);
      }
    });

    //监听排序
    table.on('sort(producCategorySystemTable)', function (obj) {
      table.reload('producCategorySystemTable', {
        initSort: obj,
        where: {
          sort: obj.field,
          order: obj.type,
        },
      });
    });
    $('#syncProductCategory').click(function () {
      layer.load(2);
      admin.req(
        'enterprise/system/admin/productCategorySystem/sync',
        {},
        function (res) {
          layer.closeAll('loading');
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        'GET',
      );
    });
    // 搜索
    form.on('submit(formSubSearchLog)', function (data) {
      insTb.reload({ where: data.field }, 'data');
    });

    // 重置搜索
    form.on('submit(resets)', function (data) {
      insTb.reload({ where: admin.resetSearch(data.field), page: { curr: 1 } }, 'data');
    });

    form.on('switch(isDeleted)', function (obj) {
      if (obj.elem.checked) {
        enable(obj.value);
      } else {
        disable(obj.value);
      }
    });

    function enable(id) {
      admin.req(
        'enterprise/system/admin/productCategorySystem/enable',
        { id: id },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            insTb.reload('producCategorySystemTable');
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        'POST',
      );
    }

    function disable(id) {
      admin.req(
        'enterprise/system/admin/productCategorySystem/disable',
        { id: id },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            insTb.reload('producCategorySystemTable');
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        'POST',
      );
    }

    // 添加按钮点击事件
    $('#producCategorySystemBtnAdd').click(function () {
      showEditModel(undefined, 'producCategorySystemForm', 'producCategorySystemFormSubmit');
    });

    // 显示编辑弹窗
    function showEditModel(data, formId, submitButton, parentIdVal) {
      let finalCategoryIds = [];
      //加载终极分类
      admin.req(
        'enterprise/system/admin/productCategorySystem/list',
        { limit: 9999 },
        function (res) {
          if (res.code == 200) {
            if (res.data != null) {
              for (let i = 0; i < res.data.length; i++) {
                if (res.data[i].isFinal == 'yes') {
                  finalCategoryIds.push(res.data[i].id);
                }
              }
            }
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        'get',
        false,
      );
      admin.open({
        type: 1,
        area: '660px',
        offset: '65px',
        title: parentIdVal ? '添加子分类' : data ? '编辑物料分类' : '添加物料分类',
        content: $('#' + formId).html(),
        success: function () {
          function treeEach(treeData, ids) {
            $.each(treeData, function (i, val) {
              if (customContains(ids, val.value)) {
                val.disabled = true;
              }
              if (val.children && val.children.length > 0) {
                treeEach(val.children, ids);
              }
            });
          }

          let customContains = function (box, val) {
            for (let i = 0; i < box.length; i++) {
              if (box[i] == val) {
                return true;
              }
            }
            return false;
          };

          if (formId != 'childForm') {
            xmSelect.render({
              el: '#selectCategory',
              model: { label: { type: 'text' } },
              radio: true,
              clickClose: true,
              filterable: true,
              tree: {
                show: true,
                strict: false,
                expandedKeys: [-1],
              },
              tips: '顶级分类',
              height: 'auto',
              data() {
                if (parentIdVal != undefined) {
                  $("input[name='parentId']").val(parentIdVal);
                }

                let treeData = tableTree.getTree(data && parentIdVal == undefined ? data.parentId : parentIdVal, data ? data.id : null);
                if (finalCategoryIds != null && finalCategoryIds.length > 0) {
                  treeEach(treeData, finalCategoryIds);
                }
                return treeData;
              },
              on: function (data) {
                //被选中的select的id,如果没有 -1
                let parentId = data.arr.length > 0 ? data.change[0].value : -1;
                $("input[name='parentId']").val(parentId);
              },
            });
          }
          //data 非空取值names
          if (!config.isEmptyObject(data)) {
            data.name = data.name.indexOf('</span>') > 0 ? data.name.split('</span>')[1] : data.name;
            data.name = data.name.indexOf('&nbsp; &nbsp;') > 0 ? (data.name.split(' &nbsp; &nbsp;').length > 2 ? data.name.split(' &nbsp; &nbsp;')[2] : data.name.split(' &nbsp; &nbsp;')[1]) : data.name;
          }

          //添加子级渲染所属分类
          if (formId == 'childForm') {
            data.code = '';
            data.name = '';
            data.description = '';
            data.status = '';
            form.val(formId, data);
            $("form input[name='parentId']").val(data.id);
            data = undefined;
          }

          if (data) {
            var option = $("form select[name='isFinal']").find('option');
            layui.each(option, function (index, item) {
              if (data.isFinal == item.text) {
                data.isFinal = item.value;
              }
            });
            if (data.type) {
              if (data.type == 'knife') {
                // 刀具
                data.type = true;
              } else if (data.type == 'cabnet') {
                // 柜子
                data.type = false;
              }
            }
          }

          form.val('producCategorySystemForm', data);
          // 表单提交事件
          form.on('submit(' + submitButton + ')', function (d) {
            layer.load(2);
            if (d.field.parentId == null || d.field.parentId == '') {
              d.field.parentId = -1;
            }
            var isDeleted = $("form input[name='isDeleted']").prop('checked');
            if (!isDeleted) {
              d.field.isDeleted = false;
            } else {
              d.field.isDeleted = true;
            }
            var isFinal = $("form input[name='isFinal']").prop('checked');
            if (!isFinal) {
              d.field.isFinal = false;
            } else {
              d.field.isFinal = true;
            }
            var type = $("form input[name='type']").prop('checked');
            if (type) {
              d.field.type = 'knife';
            } else {
              d.field.type = 'cabnet';
            }
            admin.req(
              data ? 'enterprise/system/admin/productCategorySystem/update' : 'enterprise/system/admin/productCategorySystem/add',
              d.field,
              function (res) {
                layer.closeAll('loading');
                if (res.code == 200) {
                  layer.msg(res.msg, { icon: 1 });
                  insTb.reload('producCategorySystemTable');
                  layer.closeAll('page');
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              data ? 'PUT' : 'POST',
            );
            return false;
          });
        },
      });
    }

    // 删除
    function doDelete(obj) {
      layer.confirm(
        '确定要删除吗？',
        {
          offset: '65px',
          skin: 'layui-layer-admin',
        },
        function (i) {
          layer.close(i);
          layer.load(2);
          admin.req(
            'enterprise/system/admin/productCategorySystem/' + obj.data.id,
            {},
            function (res) {
              layer.closeAll('loading');
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                obj.del();
                insTb.reload('producCategorySystemTable');
              } else {
                layer.msg(res.msg, { icon: 2 });
              }
            },
            'DELETE',
          );
        },
      );
    }

    // 导出excel
    $('#producCategorySystemBtnExport').click(function () {
      var checkRows = table.checkStatus('producCategorySystemTable');
      if (checkRows.data.length == 0) {
        layer.msg('请选择要导出的数据', { icon: 2 });
      } else {
        table.exportFile(insTb.config.id, checkRows.data, 'xls');
      }
    });
  });
</script>
